<?php declare(strict_types=1);

namespace Zyucv7\Core\Router;

use Zyucv7\Core\Router\Uri;
use Zyucv7\Core\Router\Route;
use Zyucv7\Core\Router\Dispatcher;
use Zyucv7\Core\Router\RouterException;
use Zyucv7\Core\Web\Request;

class Router
{
    private $routes = [];
    private $currentPrefix = '';

    public function get(string $route, $handler)
    {
        $this->addRoute('GET', $route, $handler);
    }

    public function post(string $route, $handler)
    {
        $this->addRoute('POST', $route, $handler);
    }

    public function group($prefix, $callback)
    {
        $oldPrefix = $this->currentPrefix;
        $this->currentPrefix .= $prefix;

        $callback($this);

        $this->currentPrefix = $oldPrefix;
    }

    private function addRoute(string $method, string $route, $handler)
    {
        $fullRoute = $this->currentPrefix . $route;
        $this->routes[] = new Route($method, $fullRoute, $handler);
    }

    public function send()
    {
        $uri = new Uri();
        $matchedRoute = null;
        $params = [];
        foreach ($this->routes as $route) {
            if ($route->match($uri->getMethod(), $uri->getPath())) {
                $matchedRoute = $route;
                $params = $route->getParams();
                break;
            }
        }
        
        if (!$matchedRoute) {
            throw RouterException::notFound($uri->getPath());
        }

        $req = Request::instance();
        foreach($params as $key => $value) {
            $req->setQuery($key, $value);
        }
        $dispatcher = new Dispatcher($matchedRoute->getHandler(), $req);
        $dispatcher->execute();
    }
}